package com.west.imserver.runnable;

import imserverentity.entity.Protocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

import com.west.imserver.handler.IHandler;
import com.west.imserver.parser.Parser;

public class IMClientRunnable implements Runnable{
	private Socket socket;
	private ObjectOutputStream oos;
	
	public IMClientRunnable() {}
	public IMClientRunnable(Socket socket, ObjectOutputStream oos) {
		this.socket = socket;
		this.oos = oos;
	}

	public void run() {
		InputStream is = null;
		ObjectInputStream ois = null;
		try {
			is = socket.getInputStream();
			ois = new ObjectInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Protocol protocol = null;
		while(true) {
			try {
				protocol = (Protocol) ois.readObject();
				System.out.println("Receive: " + protocol);
			} catch (IOException e) {
				e.printStackTrace();
				try {
					ois.close();
					is.close();
					break;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			
			//parser protocol
			IHandler handler = Parser.parse(protocol, oos);
			if (handler != null) {
				try {
					handler.handle();
				} catch (SocketException e1) {
					try {
						oos.close();
						socket.close();
						break;
					} catch (IOException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					e1.printStackTrace();
				} catch (IOException e3) {
					try {
						oos.close();
						socket.close();
						break;
					} catch (IOException e4) {
						// TODO Auto-generated catch block
						e4.printStackTrace();
					}
					e3.printStackTrace();
				}
			} else {
				
			}
		}
	}
	

}
